package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());

        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }
    /**
     * 查看流程图
     * @param id
     */
    @Override
    public InputStream getProcessImgById(Long id) {
        //根据id查询数据
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        List<String> activitiHighlist = new ArrayList<>();
        //判断状态是否是审核中
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            String instanceId = carPackageAudit.getInstanceId();
            activitiHighlist = runtimeService.getActiveActivityIds(instanceId);
        }else {
            activitiHighlist = Collections.emptyList();
        }
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmnInfoId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = generator.generateDiagram(
                repositoryService.getBpmnModel(bpmnInfo.getActProcessId()),
                activitiHighlist,
                Collections.emptyList(), "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        carPackageAuditMapper.updateStatus(id,status);
    }

    /**
     * 撤销
     * @param id
     */
    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (!carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            throw new BusinessException("套餐状态异常");
        }
        //修改状态为撤销
        carPackageAuditMapper.updateStatus(id,CarPackageAudit.STATUS_CANCEL);
        //修改单项状态为初始化状态
        serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        //将流程实例删除
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"删删删删删删删删删");

    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {

        // 根据id 查询数据 判断是否是审核中
        CarPackageAudit carPackageAudit = this.get(id);
        if (!carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            throw new BusinessException("状态异常");
        }
        //  查询任务节点
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        //  完成任务
        Map<String ,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        taskService.complete(task.getId(),map);
        // 判断是审批结果通过还是拒绝
        if (auditStatus.equals(CarPackageAudit.STATUS_PASS)){
            // 如果审核通过
            // 查询任务节点判断有没有后续
            Task task2 = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (task2==null){
                //修改单项为审核通过
                //修改carPackageAudit 为审核通过 修改info 审核时间
                serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                //同意
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                carPackageAudit.setInfo(carPackageAudit.getInfo()+ "审批人:"+ ShiroUtils.getUser().getUserName() +" 意见:同意"+ "备注:" + info);
            }else {
                //不为空将审核人修改
                carPackageAudit.setAuditorId(Long.parseLong(task2.getAssignee()));
            }

        }else{
            //修改单项为重新调整
            serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            //修改carPackageAudit 为审核拒绝 修改info 审核时间
            //拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAudit.setInfo(carPackageAudit.getInfo()+ "审批人:"+ ShiroUtils.getUser().getUserName() +" 意见:拒绝"+ "备注:" + info);

        }
        //修改时间
        carPackageAudit.setAuditTime(new Date());
        this.update(carPackageAudit);


    }


}
